import { expect } from '@jest/globals';
import * as compressing from 'compressing';
import fs from 'fs-extra';
import path from 'path';

import { hvigorOptions, initExecuteCommand, runHvigorAsync } from '../../../common/common';
import { addOhPackageDps } from '../../../plugins/common-fun';
import { AbilityType, APIType, APIVersion, LanguageType, ModuleTemplateType, RuntimeOSType, SDKType } from '../../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../../plugins/task-builder/test-case';
import { TestTaskOptionBuilder } from '../../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.FA,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility,
  },
  modulesOption: {
    [ModuleTemplateType.StaticLibraryWithC]: 1,
  },
};

const testFunBuilder: () => TestCaseFun = () => async (project, taskConfig, record) => {
  const projectRoot = project.projectRootPath();
  const options: hvigorOptions = {
    tasks: 'assembleHap',
    mode: 'module',
    product: 'default',
    module: 'entry@default',
  };
  const entryPath = project.getModule('entry').moduleRootPath();
  await addOhPackageDps(entryPath, {
    library: '../staticNativeCLibrary',
  });

  const result = await runHvigorAsync(projectRoot, initExecuteCommand(options));
  record.addStep('FA模式下，构建hap产物不丢失', result);
  expect(result.stdout).toContain('BUILD SUCCESSFUL');

  const artifactRoot = path.resolve(projectRoot, 'entry', 'build', 'default', 'outputs', 'default');
  const unzipRoot = path.join(artifactRoot, 'entry-default-unsigned');
  await compressing.zip.uncompress(path.join(artifactRoot, 'entry-default-unsigned.hap'), unzipRoot);

  const testHapArtifactPaths = [
    'assets/js/MainAbility/manifest.json',
    'assets/js/MainAbility/app.abc',
    'assets/js/MainAbility/app.js.map',
    'assets/js/MainAbility/pages/index.js.map',
    'assets/js/MainAbility/pages/index.abc',
    'libs/arm64-v8a/libc++_shared.so',
    'libs/arm64-v8a/libstaticNativeCLibrary.so',
  ];
  testHapArtifactPaths.forEach((p) => {
    if (!fs.existsSync(path.resolve(unzipRoot, p))) {
      throw new Error(`hap构建产物: ${p} 丢失`);
    }
  });
};

TestCaseBuilder.builder()
  .caseName('artifact_without_loss_fa_api10')
  .description('FA模式下，构建hap产物不丢失')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.defaultOpt())
  .testFun(testFunBuilder())
  .load();
